import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { NavController,ViewController,ToastController,Platform,NavParams, } from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';

import { TaskDetail } from '../taskdetail/taskdetail';
import { ApiService } from '../../providers/ApiService';
import { JPushService } from 'ionic2-jpush';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  loginForm: FormGroup;
  username: any;
  password: any;
  keyupstate = false;
  pushid = null;
  constructor(
    public navCtrl: NavController,
    private formBuilder: FormBuilder,
    public viewCtrl: ViewController,
    private apiService: ApiService,
    public storage: Storage,
    public toastCtrl: ToastController,
    private jPushPlugin: JPushService,
    private platform: Platform,
    private navParams: NavParams,
  ){
    this.loginForm = formBuilder.group({
      username: ['', Validators.compose([Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
    })
    this.username = this.loginForm.controls['username'];
    this.password = this.loginForm.controls['password'];
    this.storage.get('pushid').then((pushid)=>{
      if(pushid) {
        this.pushid = pushid;
      }
    })
  }
  onKey(event: any) {
    this.keyupstate=true;
  }
  private dismissHandler() {
    //console.info('Toast onDidDismiss()');
  }
  //消息提示函数
  formTip(hint){
    const toast = this.toastCtrl.create({
      message: hint,
      duration: 3000,
      position: 'middle'
    });
    toast.onDidDismiss(this.dismissHandler);
    toast.present();
    return;
  }
  goLogin(e){
    //this.viewCtrl.dismiss();
    this.apiService.login({telephone:e.username,password:e.password,registrationid:this.pushid},response => {
      if(response.json().status == 1){
        this.storage.set('mytoken', response.json().content.token)
        this.storage.set('username', response.json().content.name)
        let token = response.json().content.token;
        this.formTip(response.json().info);
        this.navCtrl.pop()
        //this.viewCtrl.dismiss(token);
      }else{
        this.formTip(response.json().info);
      }
    })
  }
  dismiss() {
    this.viewCtrl.dismiss();
  }
}
